<?php

namespace App\Http\Controllers;

use App\Http\Resources\FileResource;
use App\Models\Archive;
use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use App\Handles\Potracio\Potracio;

class FileController extends Controller
{
    public function upload(Request $request, Archive $archive, File $file)
    {
        $dir = date('Ym/d');
        $request->validate([
            'picture' => 'required|image|max:12288',
        ]);
        if ($archive) {
            $this->authorize('update', $archive);
        }
        $path = Storage::putFile('public/pictures/' . $dir, $request->file('picture'));
        $img = Image::make(Storage::path($path));
        $file->fill([
            'width' => $img->getWidth(),
            'height' => $img->getHeight(),
            'size' => Storage::size($path),
            'type' => $request->file('picture')->extension(),
            'archive_id' => $archive->id,
            'file' => $path
        ]);
        $img->destroy();
        $file->save();
        return FileResource::make($file);//Storage::url($path);
    }

    public function destroy(File $file)
    {
        $file->loadMissing('archive');
        $this->authorize('update', $file->archive);
        Storage::delete($file->file);
        $file->delete();
    }
    public function file(Request $request, File $file)
    {
        $bgArray = [
            '#CBD5E0',
            '#4A5568',
            '#A0AEC0',
            '#E2E8F0',
            '#FFF5F5',
            '#FC8181',
            '#E53E3E',
            '#ED8936',
            '#F6AD55',
            '#7B341E',
            '#C6F6D5',
            '#38A169',
            '#3182CE',
            '#4299E1',
            '#63B3ED',
            '#667EEA',
            '#9F7AEA',
            '#F687B3',
            '#ED64A6',
            '#D53F8C',
            '#553C9A'
        ];
        $img = Image::canvas($file->width, $file->height, $bgArray[rand(0, count($bgArray) - 1)]);
        $img->text($file->width . 'x' . $file->height, $file->width / 2, $file->height/2, function ($font) use ($bgArray) {
            $font->size(36);
            $font->color($bgArray[rand(0, count($bgArray) - 1)]);
        });
        $file->file = 'images/' . rand(1, 99999999) . '_' . $file->id . '.' . $file->type;
        $file->save();
        Storage::disk('local')->put('/public/' . $file->file, $img->encode($file->type));
        //return $img->encode();
        return $img->response($file->type);
    }
}
